﻿//import "~/_content/HiNcRcl/lib/ace/ace.min.js";
//import "~/_content/HiNcRcl/lib/ace/ext-language_tools.min.js";
//import "~/_content/HiNcRcl/lib/ace/theme-textmate.min.js";
//import "~/_content/HiNcRcl/lib/ace/mode-csharp.min.js";
import "../../lib/ace/ace.min.js";
import "../../lib/ace/ext-language_tools.min.js";
import "../../lib/ace/theme-textmate.min.js";
import "../../lib/ace/mode-csharp.min.js";
import "../../lib/ace/mode-json.min.js";
import "../../lib/ace/mode-markdown.min.js";
import "../../lib/ace/mode-xml.min.js";
import "../../lib/ace/mode-text.min.js";
import "../../js/ace-mode-ext.js";

export function initEditor(domEditorDiv, csThis, editorValue, mode, completions, isInitHeightByContent) {
    //console.log(completions);
    if (domEditorDiv == null)
        return;
    let editor = ace.edit(domEditorDiv);
    domEditorDiv.editor = editor;
    //console.log('initEditor', domEditorDiv.id, editorValue);
    //console.log(editorValue);
    //console.log(editor);
    //console.log(editor.getSession().getValue());
    editor.textInput.getElement().id = "ace-textarea-" + domEditorDiv.id;

    ace.config.set('basePath', '/_content/CommonRcl/lib/ace/');

    let session = ace.createEditSession(editorValue ?? '');
    editor.setSession(session);

    editor.session.setMode("ace/mode/" + mode);
    editor.setTheme("ace/theme/textmate");
    // enable autocompletion and snippets
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true,
        fontSize: "100%",
        minLines: 3
    });
    editor.on('input', async function () {
        //console.log('input');
        //console.log(editor);
        //console.log(editor.getSession());
        //console.log(editor.getSession().getValue());
        let text = editor.getSession().getValue();
        //console.log('input2', text.length);

        //let blob = new Blob([text], { type: 'text/plain' });
        //let stream = csThis.createStreamReference(blob);
        //await csThis.invokeMethodAsync('JsSetEditorTextByStream', stream);
        csThis.invokeMethodAsync('JsSetEditorText', text);
    });
    if (completions != null) {
        if (mode == 'csharp') {
            var rhymeCompleter = {
                getCompletions: function (editor, session, pos, prefix, callback) {
                    //Region C#
                    var wordList = ["yield", "foreach"];
                    callback(null, wordList.map(function (word) {
                        return {
                            caption: word,
                            value: word,
                            meta: "keyword"
                        };
                    }));

                    var wordList = ["IEnumerable"];
                    callback(null, wordList.map(function (word) {
                        return {
                            caption: word,
                            value: word,
                            meta: "class"
                        };
                    }));

                    callback(null, completions);
                },
                getDocTooltip: function (item) {
                    //console.log('getDocTooltip.item', item);
                    if (item.meta == 'property' || item.meta == 'function') {
                        item.docHTML = [
                            "<b>", item.caption, "</b>", " - ", item.classExt,
                            "<hr></hr>",
                            item.docContentHtml
                        ].join("");
                    }
                }
            }
            editor.completers = [rhymeCompleter];
        }
        else if (mode =='nc') {
            var rhymeCompleter = {
                getCompletions: function (editor, session, pos, prefix, callback) {
                    let line = session.getLine(pos.row);
                    if (!line.slice(0, pos.column).includes(";@")) {
                        callback(null, []); // Don't show any completions
                        return;
                    }
                    callback(null, completions);
                },
                getDocTooltip: function (item) {
                    //console.log('getDocTooltip.item', item);
                    if (item.meta == 'property' || item.meta == 'function') {
                        item.docHTML = [
                            "<b>", item.caption, "</b>", " - ", item.classExt,
                            "<hr></hr>",
                            item.docContentHtml
                        ].join("");
                    }
                }
            }
            editor.completers = [rhymeCompleter];

        }
    }

    editor.on('change', function () {
        if (editor.completer && editor.completer.popup) {
            editor.completer.popup.container.style.width = "40%";
        }
    });

    if (isInitHeightByContent) {
        let lineCount = editor.session.getLength();
        let fixedLineHeight = 20;
        let lineHeight = editor.renderer.lineHeight || fixedLineHeight;
        let totalHeight = lineHeight * lineCount;
        //preserve 21px for scroll bar.
        domEditorDiv.style.height = totalHeight + 24 + 'px';
    }
}
export function getLineCount(domEditorDiv) {
    let editor = domEditorDiv.editor;
    let lineCount = editor.session.getLength();
    return lineCount;
}
export function setEditorMode(domEditorDiv, mode) {
    domEditorDiv?.editor?.session?.setMode("ace/mode/" + mode);
}

export function getEditorText(domEditorDiv) {
    return domEditorDiv.editor.getValue();
}

export function dispose(domEditorDiv) {
    if (domEditorDiv == null)
        return;
    domEditorDiv.editor.on('input', null);

    //console.log('destroy.A', domEditorDiv.id);
    domEditorDiv.editor.destroy();
    domEditorDiv.remove();
    //console.log('destroy.B', domEditorDiv.id);
}
export function setEditorValue(domEditorDiv, text) {
    if (domEditorDiv == null)
        return;
    let session = domEditorDiv.editor.getSession();
    //console.log('setEditorValue', domEditorDiv.id, text);
    if (session != null)
        session.setValue(text);
}

export function setEditorReadOnly(domEditorDiv, b) {
    if (domEditorDiv == null)
        return;
    let editor = domEditorDiv.editor;
    if (b)
        editor.container.classList.add("bg-secondary-subtle");
    else
        editor.container.classList.remove("bg-secondary-subtle");
    editor.setReadOnly(b);
}